import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as categoryApi from '@/api/category'
import type { Category, CategoryStats } from '@/api/category'

export const useCategoryStore = defineStore('category', () => {
  // 状态
  const categories = ref<Category[]>([])
  const systemCategories = ref<Category[]>([])
  const categoryStats = ref<CategoryStats[]>([])
  const currentCategory = ref<Category | null>(null)
  const isLoading = ref(false)

  // 计算属性
  const userCategories = computed(() => {
    return categories.value.filter(category => !category.is_system)
  })

  const activeCategories = computed(() => {
    return categories.value.filter(category => category.is_active)
  })

  const sortedCategories = computed(() => {
    return [...categories.value].sort((a, b) => {
      if (a.sort !== b.sort) {
        return a.sort - b.sort
      }
      return a.id - b.id
    })
  })

  const categoryMap = computed(() => {
    const map: Record<number, Category> = {}
    categories.value.forEach(category => {
      map[category.id] = category
    })
    return map
  })

  /**
   * 加载分类列表
   */
  const loadCategories = async () => {
    try {
      isLoading.value = true

      const categoryList = await categoryApi.getCategories()
      categories.value = categoryList

      return categoryList

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 加载系统分类模板
   */
  const loadSystemCategories = async () => {
    try {
      const templates = await categoryApi.getCategoryTemplates()
      systemCategories.value = templates
      return templates
    } catch (error) {
      throw error
    }
  }

  /**
   * 加载分类统计
   */
  const loadCategoryStats = async () => {
    try {
      const stats = await categoryApi.getCategoryStats()
      categoryStats.value = stats
      return stats
    } catch (error) {
      throw error
    }
  }

  /**
   * 创建分类
   */
  const createCategory = async (data: categoryApi.CreateCategoryData) => {
    try {
      isLoading.value = true

      const newCategory = await categoryApi.createCategory(data)
      categories.value.push(newCategory)

      return newCategory

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 更新分类
   */
  const updateCategory = async (id: number, data: categoryApi.UpdateCategoryData) => {
    try {
      isLoading.value = true

      const updatedCategory = await categoryApi.updateCategory(id, data)

      // 更新列表中的分类
      const index = categories.value.findIndex(category => category.id === id)
      if (index !== -1) {
        categories.value[index] = updatedCategory
      }

      if (currentCategory.value?.id === id) {
        currentCategory.value = updatedCategory
      }

      return updatedCategory

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 删除分类
   */
  const deleteCategory = async (id: number) => {
    try {
      isLoading.value = true

      await categoryApi.deleteCategory(id)

      // 从列表中移除
      categories.value = categories.value.filter(category => category.id !== id)

      if (currentCategory.value?.id === id) {
        currentCategory.value = null
      }

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 分类排序
   */
  const sortCategories = async (sorts: categoryApi.SortCategoryData[]) => {
    try {
      isLoading.value = true

      await categoryApi.sortCategories(sorts)

      // 更新本地排序
      sorts.forEach(sortItem => {
        const category = categories.value.find(c => c.id === sortItem.id)
        if (category) {
          category.sort = sortItem.sort
        }
      })

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 切换分类状态
   */
  const toggleCategoryActive = async (id: number) => {
    try {
      const updatedCategory = await categoryApi.toggleCategoryActive(id)

      // 更新列表
      const index = categories.value.findIndex(category => category.id === id)
      if (index !== -1) {
        categories.value[index] = updatedCategory
      }

      if (currentCategory.value?.id === id) {
        currentCategory.value = updatedCategory
      }

      return updatedCategory

    } catch (error) {
      throw error
    }
  }

  /**
   * 复制系统分类
   */
  const copySystemCategories = async () => {
    try {
      isLoading.value = true

      await categoryApi.copySystemCategories()

      // 重新加载分类列表
      await loadCategories()

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 根据ID获取分类
   */
  const getCategoryById = (id: number): Category | undefined => {
    return categories.value.find(category => category.id === id)
  }

  /**
   * 根据名称获取分类
   */
  const getCategoryByName = (name: string): Category | undefined => {
    return categories.value.find(category => category.name === name)
  }

  /**
   * 检查分类名称是否存在
   */
  const checkCategoryNameExists = (name: string, excludeId?: number): boolean => {
    return categories.value.some(category =>
      category.name === name && category.id !== excludeId
    )
  }

  /**
   * 获取下一个排序值
   */
  const getNextSortValue = (): number => {
    const userCats = userCategories.value
    if (userCats.length === 0) {
      return 1
    }
    const maxSort = Math.max(...userCats.map(c => c.sort))
    return maxSort + 1
  }

  /**
   * 设置当前分类
   */
  const setCurrentCategory = (category: Category | null) => {
    currentCategory.value = category
  }

  /**
   * 获取分类颜色
   */
  const getCategoryColor = (categoryId?: number): string => {
    if (!categoryId) return '#8c8c8c'

    const category = getCategoryById(categoryId)
    return category?.color || '#8c8c8c'
  }

  /**
   * 获取分类图标
   */
  const getCategoryIcon = (categoryId?: number): string => {
    if (!categoryId) return 'other'

    const category = getCategoryById(categoryId)
    return category?.icon || 'other'
  }

  /**
   * 重置状态
   */
  const resetState = () => {
    categories.value = []
    systemCategories.value = []
    categoryStats.value = []
    currentCategory.value = null
  }

  return {
    // 状态
    categories,
    systemCategories,
    categoryStats,
    currentCategory,
    isLoading,

    // 计算属性
    userCategories,
    activeCategories,
    sortedCategories,
    categoryMap,

    // 方法
    loadCategories,
    loadSystemCategories,
    loadCategoryStats,
    createCategory,
    updateCategory,
    deleteCategory,
    sortCategories,
    toggleCategoryActive,
    copySystemCategories,
    getCategoryById,
    getCategoryByName,
    checkCategoryNameExists,
    getNextSortValue,
    setCurrentCategory,
    getCategoryColor,
    getCategoryIcon,
    resetState
  }
})